package com.hzncc.scaffold.controller.Rear.Other.Task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Other.Chapter;
import com.hzncc.scaffold.entity.Other.Course;
import com.hzncc.scaffold.entity.Other.Task;
import com.hzncc.scaffold.entity.Vo.ChaptersVo;
import com.hzncc.scaffold.entity.Vo.InsertTaskVo;
import com.hzncc.scaffold.entity.Vo.TaskIdVo;
import com.hzncc.scaffold.entity.Vo.UpdateTaskVo;
import com.hzncc.scaffold.mapper.TaskMapper;
import com.hzncc.scaffold.service.ChapterService;
import com.hzncc.scaffold.service.CourseService;
import com.hzncc.scaffold.service.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.error.YAMLException;

import javax.xml.transform.Result;
import java.util.Date;
import java.util.List;

/**
 * @Author: DrunkBear
 * @Date: 2022-06-18 16:17
 * @Description: null
 */
@RequestMapping("/manage/task")
@Api(tags = "后台接口-任务相关接口")
@RestController
public class ManageTaskController {


    @Autowired
    TaskService taskService;


    @Value("${project.picAddress}")
    public String picAddress;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private TaskMapper taskMapper;

    @PostMapping("/insert")
    @ApiOperation("新增任务")
    public ResultT insert(@RequestBody InsertTaskVo insertTaskVo) {
        /**
         * chapterId
         * paperId
         * testInfo
         * title
         * type
         */
        if(StringUtils.isNotEmpty(insertTaskVo.getResourceUrl()) && insertTaskVo.getType() ==  1){
            insertTaskVo.setResourceUrl(picAddress+insertTaskVo.getResourceUrl());
        }
        Boolean flag = false;
//        if(null != insertTaskVo.getPaperId()
//                && insertTaskVo.getType() ==  1
//        ){
            Chapter chapter = new Chapter();
            if(insertTaskVo.getChapterId() != null){
                chapter = chapterService.getById(insertTaskVo.getChapterId());
            }
            Integer courseId = chapter.getCourseId();
            LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
            taskLambdaQueryWrapper.eq(Task::getChapterId,chapter.getId());
            List<Task> list = taskService.list(taskLambdaQueryWrapper);
            chapter.setTasks(list);
            Course course = courseService.getById(courseId);

            if(insertTaskVo.getType() != null){
                switch (insertTaskVo.getType()){
                    case 0:
                        course.setIsQuestionLibExercise(0);
                        break;
                    case 1:
                        course.setIsQuestionLibExercise(0);
                        break;
                    case 2:
                        course.setIsQuestionLibExercise(0);
                        break;
                    case 3:
                        course.setIsQuestionLibExercise(2);
                        break;
                    case 4:
                        course.setIsQuestionLibExercise(1);
                        break;
                }
                courseService.updateById(course);
            }
            for (Task task : list) {
                if(task.getType() == 3){
                    flag = true;
                }
            }
//        }

        if(flag){
            throw new YAMLException("该课程已部署考试，无法继续添加");
        }
        if(null != insertTaskVo.getIsFree()){
            if(insertTaskVo.getType() == 3 && insertTaskVo.getIsFree() == 1){
                throw new YAMLException("考试不能设为试看");
            }
        }
        Task task = new Task();
        task.setChapterId(insertTaskVo.getChapterId());
        task.setResourceUrl(insertTaskVo.getResourceUrl());
        task.setType(insertTaskVo.getType());
        task.setTitle(insertTaskVo.getTitle());
        task.setExamStart(insertTaskVo.getExamStart() !=null ?insertTaskVo.getExamStart():null);
        task.setExamEnd(insertTaskVo.getExamEnd() !=null ?insertTaskVo.getExamEnd():null);
        task.setTestInfo(insertTaskVo.getTestInfo());
        task.setExamType(insertTaskVo.getExamType());
        task.setQuestionLibId(insertTaskVo.getQuestionLibId());
        task.setPaperId(insertTaskVo.getPaperId());
        task.setCreateTime(DateUtil.formatTime(new Date()));
        Integer queryRank = taskMapper.queryTask(task.getChapterId());
        if(null == queryRank){
            task.setRank(1);
        }else {
            if(insertTaskVo.getRank() != null){
                LambdaQueryWrapper<Task> taskLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                taskLambdaQueryWrapper1.eq(Task::getChapterId,task.getChapterId());
                taskLambdaQueryWrapper1.eq(Task::getRank,insertTaskVo.getRank());
                taskService.update(taskLambdaQueryWrapper1);
            }else {
                task.setRank(queryRank+1);
            }
        }
        boolean save = taskService.save(task);
        if (save) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }


    @PostMapping("/update")
    @ApiOperation("修改任务")
    public ResultT update(@RequestBody UpdateTaskVo updateTaskVo) {

        Integer taskId = updateTaskVo.getTaskId();
        Task task = taskService.getById(taskId);
        Chapter chapter = chapterService.getById(task.getChapterId());
        Integer courseId = chapter.getCourseId();
        Course course = courseService.getById(courseId);
        if(updateTaskVo.getType().equals(3) && !task.getType().equals(3)){
            LambdaQueryWrapper<Chapter> chapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
            chapterLambdaQueryWrapper.eq(Chapter::getCourseId,course.getId());
            List<Chapter> chapters = chapterService.list(chapterLambdaQueryWrapper);
            for (Chapter item : chapters) {
                LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
                taskLambdaQueryWrapper.eq(Task::getChapterId,chapter.getId());
                List<Task> list = taskService.list(taskLambdaQueryWrapper);
                item.setTasks(list);
            }
            course.setChapters(chapters);
            Boolean flag = false;
            if(CollUtil.isNotEmpty(course.getChapters())){
                for (Chapter courseChapter : course.getChapters()) {
                    if(CollUtil.isNotEmpty(courseChapter.getTasks())){
                        for (Task courseChapterTask : courseChapter.getTasks()) {
                            if(courseChapterTask.getType().equals(3)){
                                flag = true;
                            }
                        }
                    }
                }
            }

        }
        if(!updateTaskVo.getType().equals(0) && StringUtils.isNotEmpty(updateTaskVo.getResourceUrl())){
            updateTaskVo.setResourceUrl(picAddress+updateTaskVo.getResourceUrl());
        }
        Boolean update = false;
        if(BeanUtil.isNotEmpty(task)){
            task.setId(taskId);
            task.setType(updateTaskVo.getType());
            task.setResourceUrl(updateTaskVo.getResourceUrl());
            task.setTitle(updateTaskVo.getTitle());
            task.setExamStart(updateTaskVo.getExamStart() !=null ?updateTaskVo.getExamStart():null);
            task.setExamEnd(updateTaskVo.getExamEnd() !=null ?updateTaskVo.getExamEnd():null);
            task.setTestInfo(updateTaskVo.getTestInfo());
            task.setExamType(updateTaskVo.getExamType());
            task.setQuestionLibId(updateTaskVo.getQuestionLibId());
            task.setPaperId(updateTaskVo.getPaperId());
            update = taskService.updateById(task);
        }

        //获取考试信息位置
        LambdaQueryWrapper<Chapter> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Chapter::getCourseId, courseId);
        List<Chapter> chapterList = chapterService.list(lqw);
        if (CollUtil.isNotEmpty(chapterList)) {
            for (Chapter chapter1 : chapterList) {
                LambdaQueryWrapper<Task> lqww = new LambdaQueryWrapper<>();
                lqww.eq(Task::getChapterId, chapter1.getId());
                List<Task> taskList = taskService.list(lqww);
                for (Task task1 : taskList) {
                    if(task1.getType().equals(0)){
                        updateTaskVo.setType(0);
                    }
                }
            }
        }

        if(updateTaskVo.getType() != null){
            switch (updateTaskVo.getType()){
                case 0:
                    course.setIsQuestionLibExercise(0);
                    break;
                case 1:
                    course.setIsQuestionLibExercise(0);
                    break;
                case 2:
                    course.setIsQuestionLibExercise(0);
                    break;
                case 3:
                    course.setIsQuestionLibExercise(2);
                    break;
                case 4:
                    course.setIsQuestionLibExercise(1);
                    break;
            }
            courseService.updateById(course);
        }
        if (update) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }

    @PostMapping("/delete")
    @ApiOperation("删除任务")
    public ResultT delete(@RequestBody TaskIdVo taskIdVo) {

        boolean remove = taskService.removeById(taskIdVo.getTaskId());

        if (remove) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }

    @PostMapping("/upload")
    @ApiOperation("上传")
    public ResultT upload(String type, MultipartFile file){

        return null;
    }
}
